<?php

namespace App\Models;

use App\Libs\CommonUtils;
use function foo\func;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class VolunteerGroup extends Model
{
    //
    protected $table = 'volunteer_group';

    protected $fillable = ['user_id', 'team_id', 'name'];

    public function volunteer() {
        return $this->belongsTo('App\Models\Volunteer', 'user_id', 'user_id');
    }

    protected $appends = array('volunteers');

    public function getVolunteersAttribute()
    {
        $groupId = $this->id;
        $groupVolunteers = UserGroup::with('user', 'volunteer')->where('volunteer_group_id', $groupId)->get()->toArray();
        $userIds = array_map(function($item){
            return $item['user_id'];
        }, $groupVolunteers);

        $projectMap = [];
        $project = DB::table('user_project')->select(DB::raw('count(*) as project_count'), 'user_id')
        ->whereIn('user_id', $userIds)->where('verify_status', '=', 1)
        ->groupby('user_id')->orderby('user_id')->get()->toArray();

        foreach ($project as $p) {
            $projectMap[$p->user_id] = $p;
        }


        $volunteers = array_map(function(&$item) use($groupId, $projectMap){
            $item['volunteer']['group_id'] = $groupId;
            $item['volunteer']['project_count'] = !empty($projectMap[$item['user_id']]) ? $projectMap[$item['user_id']]->project_count : 0;
            $item['volunteer']['phone'] = !empty($item['user']) ? $item['user']['phone'] : '';
            $item['volunteer']['username'] = !empty($item['user']) ? $item['user']['username'] : '';

            // 根据身份证识别年龄性别
            $idCard = !empty($item['volunteer']) ? $item['volunteer']['id_number'] : '';
            if(!empty($idCard) && CommonUtils::isIdCard($idCard)){
                $item['volunteer']['age'] = CommonUtils::get_age($idCard);
                $item['volunteer']['sex'] = CommonUtils::get_sex($idCard);
            } else if (!empty($item['volunteer']['birthday'])){
                $item['volunteer']['age'] = intval(date('Y')) - intval(explode('-',$item['volunteer']['birthday'])[0]) + 1;
            } else {
                $item['volunteer']['age'] = '';
            }
            return $item['volunteer'];
        }, $groupVolunteers);
        return $volunteers;
    }

}
